package com.mlm.mlmapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.HairDresserDetailHeaderFragment;
import com.mlm.mlmapp.adapter.view.HairDresserDetailItemFragment;
import com.mlm.mlmapp.adapter.view.adapter.HairDresserDetailAdapter;
import com.mlm.mlmapp.adapter.view.listener.DresserDetailClickListener;
import com.mlm.mlmapp.adapter.view.listener.DresserDetailHeaderSelectedListener;
import com.mlm.mlmapp.cons.Constants;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.hairdress_detail)
public class HairDresserDetailActivity extends BaseActivity implements HTTPCons {
    public static final int REQUEST_CODE = 11;

    public static final int REQUEST_CODE_DRESSER_COLLECTION = 911;
    public static final int REQUEST_CODE_STYLE_COLLECTION = 912;

    public static final int RESULT_DRESSER_COLLECTION = 901;
    public static final int RESULT_STYLE_COLLECTION = 902;
    private AQuery aq;
    private HairDresserDetailAdapter adapter;
    HairDresserDetailHeaderFragment headerFragment;
    @Pref
    Prefs_ myPrefs;
    @Extra
    String id;
    String dresser_name;
    String dresser_url;
    @DimensionRes(R.dimen.recyclerview_sylist_space)
    float recyclerview_sylist_space;
    private String leveName;
    private String awards;
    private String dresser_id;
    @ViewById
    ViewPager pager;
    private List<Fragment> contents;
    private float centerX;
    private int type = 0;
    private AjaxCallback<JSONObject> collectCB;
    // 首先在您的Activity中添加如下成员变量
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");

    private SocializeListeners.SnsPostListener snsPostListener;

    @AfterViews
    public void init() {
        com.umeng.socialize.utils.Log.LOG = true;
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }
        contents = new ArrayList<Fragment>();
        setTranStatusBar();
        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        pager.setPageMargin((int) this.getResources().getDimension(
                R.dimen.dresser_detail_viewpager_margin));
        centerX = pager.getX();
        pager.setX(this.getResources().getDimension(
                R.dimen.dresser_detail_viewpager_first_margin_left));

        pager.setOnPageChangeListener(new DresserDetailOnPageChangedListener(
                pager));
        adapter = new HairDresserDetailAdapter(
                HairDresserDetailActivity.this.getSupportFragmentManager(),
                contents);
        pager.setAdapter(adapter);
        pager.setCurrentItem(0);// 设置当前显示标签页为第一页
        pager.setOffscreenPageLimit(10);
        getFragmentsAction();

    }

    void refreshAction() {
        myPrefs = new Prefs_(this);
        String url = get_dresser_detail_action + id + "&mobile="
                + myPrefs.loginID().get();

        aq.progress(new AQProgressDialog(this)).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject object,
                                 AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                // TODO Auto-generated method stub
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {

                    int dresserCollections = getJsonInt(object, "collected");
                    ((HairDresserDetailHeaderFragment) contents.get(0))
                            .setCounts(dresserCollections);
                    if (getJsonInt(object, "isCollect") == 1) {
                        ((HairDresserDetailHeaderFragment) contents.get(0))
                                .setCollect(false);
                    } else {
                        ((HairDresserDetailHeaderFragment) contents.get(0))
                                .setCollect(true);
                    }
                    JSONArray array = getJsonArray(object, "opusInfos");
                    if (array != null) {
                        for (int i = 0; i < array.length(); i++) {
                            try {
                                JSONObject obj = array.getJSONObject(i);
                                ((HairDresserDetailItemFragment) contents
                                        .get(i + 1)).setCounts(getJsonInt(obj,
                                        "collectCount"));
                                if (getJsonInt(obj, "isCollect") == 1) {
                                    ((HairDresserDetailItemFragment) contents
                                            .get(i + 1))
                                            .setCollectionStatus(false);
                                } else {
                                    ((HairDresserDetailItemFragment) contents
                                            .get(i + 1))
                                            .setCollectionStatus(true);
                                }

                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                    }
                }
            }

        });
    }

    void getFragmentsAction() {

        String url = get_dresser_detail_action + id + "&mobile="
                + myPrefs.loginID().get();

        aq.progress(new AQProgressDialog(this)).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject object,
                                 AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                // TODO Auto-generated method stub
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {

                    try {
//                        "leveName" -> "风格设计师"
//                        "awards" -> "最佳美发师"
                        leveName = CommonUtils.getJsonString(object, "leveName");
                        awards = CommonUtils.getJsonString(object, "awards");
                        dresser_id = CommonUtils.getJsonString(object, "id");
                        dresser_name = CommonUtils.getJsonString(object, "name");
                        dresser_url = CommonUtils.getJsonString(object, "iconPhotoUrl");
                        headerFragment = new HairDresserDetailHeaderFragment(
                                HairDresserDetailActivity.this,
                                new DresserDetailHeaderSelectedListener() {

                                    @Override
                                    public void onItemClick(View v, int position) {
                                        // TODO Auto-generated method stub
                                    }

                                    @Override
                                    public void onCommentsAllClick(String tid) {
                                        // TODO Auto-generated method stub
                                        DresserCommentsListActivity_
                                                .intent(HairDresserDetailActivity.this)
                                                .extra("dresserid", id).start();
                                    }

                                    @Override
                                    public void onAppointment(String sid) {
                                        // TODO Auto-generated method stub
                                        BookActivity_
                                                .intent(HairDresserDetailActivity.this)
                                                .extra("id", id).start();
                                    }

                                    @Override
                                    public void onCollectClick(int status) {
                                        // TODO Auto-generated method stub
                                        onCollectionDresserClick(id, status);
                                    }
                                }, myPrefs.loginID().get());
                        Bundle args = new Bundle();
                        args.putString(JSON, object.toString());
                        headerFragment.setArguments(args);
                        contents.add(headerFragment);
                        JSONArray array = getJsonArray(object, "opusInfos");
                        if (array != null) {
                            for (int i = 0; i < array.length(); i++) {
                                // 新建Fragment的实例对象，并设置参数传递到Fragment中
                                final int index = i;
                                Bundle pagerArgs = new Bundle();
                                HairDresserDetailItemFragment content = new HairDresserDetailItemFragment(
                                        HairDresserDetailActivity.this,
                                        new DresserDetailClickListener() {

                                            @Override
                                            public void onItemClicked(String id,String linkType) {
                                                // TODO Auto-generated method
                                                // stub
                                                if ("2".equals(linkType)) {
                                                    HairStylePublicDetailActivity_
                                                            .intent(HairDresserDetailActivity.this)
                                                            .extra("id", id)
                                                            .start();
                                                }else{
                                                    HairStyleDetailActivity_
                                                            .intent(HairDresserDetailActivity.this)
                                                            .extra("id", id)
                                                            .start();
                                                }

                                            }

                                            @Override
                                            public void onAppointmentClick(
                                                    String sid) {
                                                // TODO Auto-generated method
                                                // stub
                                                BookActivity_
                                                        .intent(HairDresserDetailActivity.this)
                                                        .extra("id", id)
                                                        .extra("styleid", sid)
                                                        .start();
                                            }

                                            @Override
                                            public void onCollectClick(
                                                    String id, int status) {
                                                // TODO Auto-generated method
                                                // stub
                                                onCollectionStyleClick(id,
                                                        status, index);

                                            }
                                        }, myPrefs.loginID().get());

                                pagerArgs.putString(JSON, array
                                        .getJSONObject(i).toString());

                                content.setArguments(pagerArgs);
                                contents.add(content);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }

        });

    }


    public class DresserDetailOnPageChangedListener implements
            OnPageChangeListener {
        ViewPager root;

        public DresserDetailOnPageChangedListener(ViewPager root) {
            this.root = root;

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
            if (root != null) {
                root.invalidate();
            }
        }

        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub
            if (arg0 == 0) {
                root.setX(getResources().getDimension(
                        R.dimen.dresser_detail_viewpager_first_margin_sec));
            }
            if (arg0 < contents.size() - 1 && arg0 > 0) {
                root.setX(centerX
                        + getResources()
                        .getDimension(
                                R.dimen.dresser_detail_viewpager_first_margin_cen));
            }
            // if(arg0==contents.size()-1){
            //
            //
            // root.setX(getResources().getDimension(R.dimen.dresser_detail_viewpager_first_margin_right));
            // }

        }

    }

    @OnActivityResult(REQUEST_CODE_DRESSER_COLLECTION)
    void onResultDresser(int resultcode, Intent data) {
        if (resultcode == RESULT_DRESSER_COLLECTION) {
            if (data != null) {
                onCollectionDresserClick(data.getStringExtra("collectionid"),
                        data.getIntExtra("collectionstatus", 0));

            }

        }
    }

    @OnActivityResult(REQUEST_CODE_STYLE_COLLECTION)
    void onResultStyle(int resultcode, Intent data) {
        if (resultcode == RESULT_STYLE_COLLECTION) {
            if (data != null)
                onCollectionStyleClick(data.getStringExtra("collectionid"), 2,
                        data.getIntExtra("index", -1));
        }
    }

    public void onCollectionDresserClick(String id, int status) {
        // TODO Auto-generated method stub
        // current status stand for the oppsite collect type
        if ("0".equals(myPrefs.loginID().get())) {
            LoginActivity_.intent(this).extra("collectionid", id)
                    .extra("collectionstatus", status)
                    .startForResult(REQUEST_CODE_DRESSER_COLLECTION);
            return;
        } else {
            // update();
        }

        if (status == 1) {
            type = 2;
        } else {
            type = 1;
        }
        aq = new AQuery(this);
        collectCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {

                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {

                            if (type == 1) {
                                headerFragment.setCollect(false);
                                // Toast.makeText(aq.getContext(), "收藏成功",
                                // Toast.LENGTH_SHORT).show();
                            } else {
                                headerFragment.setCollect(true);
                                // Toast.makeText(aq.getContext(), "取消收藏成功",
                                // Toast.LENGTH_SHORT).show();
                            }
                            refreshAction();
                            CommonUtils.sendBroadCast(HairDresserDetailActivity.this, CollectionsActivity.COLLECTION_REFRESH, "refreshflag", "0");
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", myPrefs.loginID().get()));
        pairs.add(new BasicNameValuePair("stylistId", this.id));
        pairs.add(new BasicNameValuePair("type", type + ""));
        CommonUtils.postRequest(collect_hairdresser_action, aq, collectCB,
                pairs);
    }

    public void onCollectionStyleClick(String id, int status, final int index) {
        // TODO Auto-generated method stub
        // current status stand for the oppsite collect type
        if ("0".equals(myPrefs.loginID().get())) {
            LoginActivity_.intent(this).extra("collectionid", id)
                    .extra("collectionstatus", status).extra("index", index)
                    .startForResult(REQUEST_CODE_STYLE_COLLECTION);
            return;
        } else {
            // update();
        }
        if (status == 1) {
            type = 2;
        } else {
            type = 1;
        }
        aq = new AQuery(this);
        collectCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        HairDresserDetailItemFragment fragement = (HairDresserDetailItemFragment) contents
                                .get(index + 1);

                        if (html.getBoolean("isSuccess")) {
                            if (type == 1) {
                                fragement.setCollectionStatus(false);
                                // Toast.makeText(aq.getContext(), "收藏成功",
                                // Toast.LENGTH_SHORT).show();
                            } else {
                                fragement.setCollectionStatus(true);
                                // Toast.makeText(aq.getContext(), "取消收藏成功",
                                // Toast.LENGTH_SHORT).show();
                            }

                            refreshAction();
                            CommonUtils.sendBroadCast(HairDresserDetailActivity.this, CollectionsActivity.COLLECTION_REFRESH, "refreshflag", "0");
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", myPrefs.loginID().get()));
        pairs.add(new BasicNameValuePair("opusInfoId", id));
        pairs.add(new BasicNameValuePair("type", type + ""));
        CommonUtils.postRequest(collect_hairstyle_action, aq, collectCB, pairs);
    }

    @Click
    void iv_share() {

//		final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] {
//				SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA };

// 参数1为Context类型对象， 参数2为要分享到的目标平台， 参数3为分享操作的回调接口

        snsPostListener = new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int stCode,
                                   SocializeEntity entity) {
                if (stCode == 200) {
                    Toast.makeText(HairDresserDetailActivity.this, "分享成功", Toast.LENGTH_SHORT)
                            .show();

                } else {
                }
            }
        };
        mController.registerListener(snsPostListener);
        //默认分享列表中存在的平台如果需要删除，则调用下面的代码：
        mController.getConfig().removePlatform(SHARE_MEDIA.TENCENT);
        configPlatforms();
        setShareContent();

        mController.openShare(HairDresserDetailActivity.this, false);

        // new ShareAction(this).setDisplayList(displaylist).withText("呵呵")
        // .withTitle("title").withTargetUrl("http://www.baidu.com")
        // .withMedia(image)
        // .setListenerList(umShareListener, umShareListener)
        // .setShareboardclickCallback(shareBoardlistener).open();
    }

    /**
     * 配置分享平台参数</br>
     */
    private void configPlatforms() {
        // 添加新浪SSO授权
        mController.getConfig().setSsoHandler(new SinaSsoHandler());

        // 添加微信、微信朋友圈平台
        addWXPlatform();
    }


    /**
     * @return
     * @功能描述 : 添加微信平台分享
     */
    private void addWXPlatform() {
        // 注意：在微信授权的时候，必须传递appSecret
        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appId = "wxe94f6ebf0daa4bda";
        String appSecret = "e2f4f10444b6399f18e151737a0b653e";
        // 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(HairDresserDetailActivity.this, appId, appSecret);
        wxHandler.addToSocialSDK();

        // 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(HairDresserDetailActivity.this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    /**
     * 根据不同的平台设置不同的分享内容</br>
     */
    private void setShareContent() {
        // 配置SSO
//        mController.getConfig().setSsoHandler(new SinaSsoHandler());


        UMImage localImage = new UMImage(getApplicationContext(), dresser_url);
//
        WeiXinShareContent weixinContent = new WeiXinShareContent();
        weixinContent.setShareContent(Constants.SHARE_STYINFO);
        weixinContent.setTitle(Constants.SHARE_STYTITLE);
        weixinContent.setTargetUrl(webhost + "/Home/Share/stylist/sid/" + id);
        weixinContent.setShareMedia(localImage);
        mController.setShareMedia(weixinContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(Constants.SHARE_STYINFO);
        circleMedia.setTitle(Constants.SHARE_STYTITLE);
        circleMedia.setShareMedia(localImage);
        circleMedia.setTargetUrl(webhost + "/Home/Share/stylist/sid/" + id);
        mController.setShareMedia(circleMedia);
//
        SinaShareContent sinaContent = new SinaShareContent();
        sinaContent.setTitle(Constants.SHARE_STYTITLE);
        sinaContent.setShareContent(Constants.SHARE_STYINFO + webhost + "/Home/Share/stylist/sid/" + id);
        sinaContent.setShareMedia(localImage);
        sinaContent.setTargetUrl(webhost + "/Home/Share/stylist/sid/" + id);
        mController.setShareMedia(sinaContent);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }


    }

    @Click
    void iv_back() {
        this.finish();
    }
}
